#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    By :陈狍子 e4ting@qq.com 2024-12-07 22:10:19
"""
import sys,os
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from e4ting import util,log

from .roundutil import (
    DealCardsRound,
    PreFlopRound,
    FlopRound,
    TurnRound,
    RiverRound,
    )

from .texas import Judge
from core.cache    import GameCache

class Game(object):
    """ 游戏抽象类 """
    def __init__(self, btn=0, room=None):
        self.players = []
        self.rounds  = []
        self.btn     = btn
        self.room    = room
        self.uid     = f"{self.room.uid}_{self.btn}"

        self.round_index = 0

    def broadcast(self, msg):
        return self.room.broadcast(msg)

    @property
    def cache(self):
        cache = GameCache(self.uid)
        if not cache.exists():
            cache.set(__time__=util.now())
        return cache

    def init(self):
        # 裁判
        self.judge = Judge(self.btn, game=self)
        self.judge.init()
        self.room.upadte(self.judge)
        self.rounds = [
            DealCardsRound(self.btn, game=self, judge=self.judge),
            PreFlopRound(  self.btn, game=self, judge=self.judge),
            FlopRound(     self.btn, game=self, judge=self.judge),
            TurnRound(     self.btn, game=self, judge=self.judge),
            RiverRound(    self.btn, game=self, judge=self.judge),
        ]
        log.info("新开一局游戏")
        self.broadcast("新开一局游戏")
        self.cache.set(judge=self.judge.uid)

    def set_players(self, players):
        self.players = players

    def clear_player_cache(self):
        for player in self.players:
            player.clear_cache("pos", "total_bet", "bet")

    def webdump(self):
        return dict(
            uid=self.uid,
            players=[p.webdump() for p in self.players],
            rounds=[r.webdump() for r in self.rounds[:self.round_index+1] ]
            )

    def run(self):
        self.judge.set_players(self.players)
        # self.room.clear_all_rate()
        log.info("庄家位是 {self.btn}".format(self=self))
        self.broadcast("庄家位是 {self.btn}".format(self=self))
        for i,_round in enumerate(self.rounds):
            self.round_index = i
            self.room.update_game(self)
            _round.set_players(self.players)
            _round.init()
            _round.run()
        self.judge.get_winner()
        self.judge.rewards()
        self.judge.quit()
        self.clear_player_cache()

